package com.aurora.leetcode.answer;

/**
 * @author : Aurora
 * @date : 2024/4/18 09:28
 * @description 移除链表元素
 * 给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点
 */
public class RemoveElements_203 {
    public ListNode removeElements(ListNode head, int val) {
        ListNode p = head;
        ListNode pre = new ListNode();
        pre.next = head;
        head = pre;
        while(p != null){
            if(p.val == val){
                pre.next = p.next;
            }else{
                pre = p;
            }
            p = p.next;
        }
        return head.next;
    }

    //改进
    public ListNode removeElementsImpr(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode p = dummy;
        while(p.next != null){
            if(p.next.val == val){
                p.next = p.next.next;
            }else{
                p = p.next;
            }
        }
        return dummy.next;
    }

    public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
